package com.doublefish.doublefishrobot.ui.home;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.doublefish.doublefishrobot.R;
import com.doublefish.doublefishrobot.base.BaseActivity;
import com.doublefish.doublefishrobot.ui.home.adapter.AddDeviceListAdapter;
import com.doublefish.doublefishrobot.ui.home.bean.DeviceBean;
import com.doublefish.doublefishrobot.ui.home.s6.S6ModeMenuActivty;
import com.doublefish.doublefishrobot.ui.home.s8.S8ModeMenuActivty;
import com.doublefish.doublefishrobot.utils.AppCacheUtil;
import com.doublefish.doublefishrobot.utils.MessageEvent;
import com.doublefish.doublefishrobot.utils.ble.DFBleManager;
import com.doublefish.doublefishrobot.utils.ble.DFS6ProtocolManager;
import com.doublefish.doublefishrobot.utils.ble.DFS8ProtocolManager;
import com.doublefish.doublefishrobot.utils.ble.bean.ModeConstant;
import com.doublefish.doublefishrobot.utils.ble.bean.OnBleResponseHandler;
import com.doublefish.doublefishrobot.utils.db.DataBaseApi;
import com.doublefish.doublefishrobot.widget.CommonDialog;
import com.doublefish.doublefishrobot.widget.LoadingDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作者:dugaofeng on 2024/12/17 09:34
 */
public class DevicesBindBleActivity extends BaseActivity implements DFBleManager.OnBleManagerListner{

    @BindView(R.id.tv_title)
    TextView titleTV;

    @BindView(R.id.tv_right)
    TextView rightTV;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private int protocolType = ModeConstant.ProtocolTypeUnkonw;
    private AddDeviceListAdapter adapter;
    private List<DeviceBean> searchList = new ArrayList<>(); //已搜索设备列表
    private List<DeviceBean> bindList = new ArrayList<>(); //已绑定设备列表

    private List<AddDeviceListAdapter.BleDeviceEntity> showList = new ArrayList<>();


    public static Intent makeIntent(Context context, int protocolType) {
        Intent intent = new Intent(context, DevicesBindBleActivity.class);
        intent.putExtra("protocolType", protocolType);
        return intent;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_device_bind_ble;
    }

    @Override
    protected void initView() {

        adapter = new AddDeviceListAdapter(this, showList);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                AddDeviceListAdapter.BleDeviceEntity entity = showList.get(position);
                if (entity.isHeader() || entity.isBind()) {
                    return;
                }
                if (position == 1 && entity.getDeviceBean() == null) {
                    showEmptyAlert();
                    return;
                }
                bindItem(entity.getDeviceBean());
            }
        });
    }

    @Override
    protected void initListener() {
        rightTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startScanBle();
            }
        });
        rightTV.setBackground(getResources().getDrawable(R.mipmap.icon_refresh_2));
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        protocolType = intent.getIntExtra("protocolType", 0);

        String title = "";
        if (protocolType == ModeConstant.ProtocolTypeS8) {
            title = getString(R.string.super_8_robot);
        } else if (protocolType == ModeConstant.ProtocolTypeS6) {
            title = getString(R.string.super_6_robot);
        }
        titleTV.setText(title);

        filterDeviceWithType();
        generateShowList();
    }

    @Override
    public void onResume() {
        super.onResume();
        DFBleManager.getInstance().setOnBleManagerListner(this);

        startScanBle();
    }

    @Override
    protected void onPause() {
        super.onPause();

        stopScan();
    }

    //扫描蓝牙设备
    private void startScanBle() {
        if (!DFBleManager.getInstance().canScan()) {
//            showToast("无法使用蓝牙搜索，请检查蓝牙");
            return;
        }
//        showIndicatorView("开始扫描蓝牙设备");
        DFBleManager.getInstance().startBleScan();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //10秒后 停止搜索
//                hideIndicatorView();
                stopScan();
            }
        }, 10000);
    }

    private void stopScan() {
        DFBleManager.getInstance().stopBleScan();
    }

    @OnClick(R.id.ll_back)
    public void onBackClick() {
        finish();
    }

    private void bindItem(DeviceBean bindBean) {
        DataBaseApi.saveDeviceInfo(bindBean, new DataBaseApi.OnDatabaseCommonListner() {
            @Override
            public void onCallback(boolean suc) {
                if (suc) {
                    //刷新数据
                    searchList.remove(bindBean);
                    bindList.add(0, bindBean);
                    generateShowList();

                    EventBus.getDefault().post(new MessageEvent(MessageEvent.BIND_DEVICES_CHANGED_NOTI, null));
                    showBindResultAlert(bindBean);
                } else {
                    showToast( getString(R.string.fail_added));
                }
            }
        });
    }

    private void showBindResultAlert(DeviceBean deviceBean) {
        String title = getString(R.string.success_added);
        String msg = getString(R.string.connect_serve_alert);
        CommonDialog dialog = new CommonDialog(this, title, msg, new CommonDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
               if (confirm) {
                   //连接发球机
                   connectBle(deviceBean);
               }
            }
        });
        dialog.setNegativeButton(getString(R.string.cancel));
        dialog.setPositiveButton(getString(R.string.connect));
        dialog.show();
    }

    private void showEmptyAlert() {
        String title = getString(R.string.no_ble_tips);
        String msg = getString(R.string.ble_help_tips);
        CommonDialog dialog = new CommonDialog(this, title, msg, new CommonDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    startScanBle();
                }
            }
        });
        dialog.setNegativeButton(getString(R.string.cancel));
        dialog.setPositiveButton(getString(R.string.refresh));
        dialog.show();
    }

    private void connectBle(DeviceBean deviceBean) {
        showLoadingDialog();
        DFBleManager.getInstance().connectBt(deviceBean.getTid(), deviceBean.getMac(), deviceBean.getName(), deviceBean.getDeviceType());
    }

    private void connectMachine() {
        if (DFBleManager.getInstance().curDeviceIsProtocolTypeS8()) {
            DFS8ProtocolManager.getInstance().connectMachine(new OnBleResponseHandler() {
                @Override
                public boolean onResponse(boolean success, int status, Object res) {
                    if (success) {
                        toS8ModeMenu();
                    } else {
                        showToast(getString(R.string.fail_machine_id));
                    }
                    return false;
                }
            });
        } else if (DFBleManager.getInstance().curDeviceIsProtocolTypeS6()) {
            DFS6ProtocolManager.getInstance().connectMachine(new OnBleResponseHandler() {
                @Override
                public boolean onResponse(boolean success, int status, Object res) {
                    if (success) {
                        toS6ModeMenu();
                    } else {
                        showToast(getString(R.string.fail_machine_id));
                    }
                    return false;
                }
            });
        }
    }

    private LoadingDialog loadingDialog = null;
    private void showLoadingDialog() {
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(this);
        }
        loadingDialog.setMsg(getString(R.string.ble_connecting_tips));
        if (!loadingDialog.isShowing()) {
            loadingDialog.show();
            hideLoadingDialogDelay();
        }
    }

    private void hideLoadingDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    private void hideLoadingDialogDelay() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                hideLoadingDialog();
            }
        }, 5000);
    }

    private void toS8ModeMenu() {
        Intent intent = new Intent(this, S8ModeMenuActivty.class);
        startActivity(intent);
    }

    private void toS6ModeMenu() {
        Intent intent = new Intent(this, S6ModeMenuActivty.class);
        startActivity(intent);
    }

    //region DFBleManager.OnBleManagerListner
    @Override
    public void onScanResult(List<DeviceBean> deviceBeanList) {

        filterDevice(deviceBeanList);
        generateShowList();
    }

    @Override
    public void onConnectBle(boolean success, DeviceBean deviceBean) {
        if (success) {
            showToast(getString(R.string.success_ble));
            //连接发球机
            connectMachine();
        } else {
            showToast(getString(R.string.fail_ble));
        }
    }

    @Override
    public void onDisConnectBle() {
    }

    //过滤已经添加过的设备 只显示未添加的设备
    private void filterDevice(List<DeviceBean> list) {
        List<DeviceBean> filterList = new ArrayList<>();
        for (DeviceBean bean : list) {
            if ((bean.getProtocolType() == protocolType) && !isContain(bean)) {
                filterList.add(bean);
            }
        }
        searchList.clear();
        searchList.addAll(filterList);
    }

    private boolean isContain( DeviceBean bean) {
        if (this.bindList.size() == 0) {
            return false;
        }
        for (DeviceBean deviceBean : this.bindList) {
            if (deviceBean.isSameDevice(bean)) {
                return true;
            }
        }
        return false;
    }
    private void filterDeviceWithType() {
        List<DeviceBean> list = AppCacheUtil.getInstance().getBindList();
        if (list == null || list.size() == 0) {
            return;
        }
        for (DeviceBean deviceBean : list) {
            if (deviceBean.getProtocolType() == protocolType) {
                bindList.add(deviceBean);
            }
        }
    }

    private void generateShowList() {
        showList.clear();

        AddDeviceListAdapter.BleDeviceEntity header = new AddDeviceListAdapter.BleDeviceEntity(true);
        header.setTitle(getString(R.string.bond_device));
        header.setBind(false);
        showList.add(header);

        if (searchList.size() > 0) {
            for (DeviceBean bean:searchList) {
                AddDeviceListAdapter.BleDeviceEntity entity = new AddDeviceListAdapter.BleDeviceEntity(false);
                entity.setDeviceBean(bean);
                entity.setBind(false);
                showList.add(entity);
            }
        } else {
            AddDeviceListAdapter.BleDeviceEntity entity = new AddDeviceListAdapter.BleDeviceEntity(false);
            entity.setDeviceBean(null);
            entity.setBind(false);
            showList.add(entity);
        }

        if (bindList.size() > 0){
            AddDeviceListAdapter.BleDeviceEntity header1 = new AddDeviceListAdapter.BleDeviceEntity(true);
            header1.setTitle(getString(R.string.bond_device));
            header1.setBind(true);
            showList.add(header1);

            for (DeviceBean bean:bindList) {
                AddDeviceListAdapter.BleDeviceEntity entity = new AddDeviceListAdapter.BleDeviceEntity(false);
                entity.setDeviceBean(bean);
                entity.setBind(true);
                showList.add(entity);
            }
        }

        adapter.notifyDataSetChanged();
    }
    //endregion
}

